<template>
  <div class="login-page">
    <div class="nav-header">
      <img src="../assets/icons/back.svg" class="back-icon" @click="goBack" />
      <span class="nav-title">登录</span>
    </div>

    <div class="login-container">
      <form @submit.prevent="handleLogin">
        <div class="form-group">
          <label>邮箱</label>
          <input 
            type="text" 
            v-model="email" 
            placeholder="请输入邮箱" 
            required 
            maxlength="20"
          />
        </div>
        <div class="form-group">
          <label>密码</label>
          <div class="password-wrapper">
            <input 
              :type="showPassword ? 'text' : 'password'" 
              v-model="password" 
              placeholder="请输入6位以上的密码" 
              required 
              maxlength="32"
            />
            <svg 
              @click="togglePasswordVisibility" 
              class="toggle-password" 
              xmlns="http://www.w3.org/2000/svg" 
              fill="none" 
              viewBox="0 0 24 24" 
              stroke="currentColor"
            >
              <path 
                v-if="showPassword" 
                stroke-linecap="round" 
                stroke-linejoin="round" 
                stroke-width="2" 
                d="M13.875 18.825A10.05 10.05 0 0112 19c-5.523 0-10-4.477-10-10S6.477 0 12 0s10 4.477 10 10c0 1.875-.525 3.625-1.425 5.125M15 15l5 5"
              />
              <path 
                v-else 
                stroke-linecap="round" 
                stroke-linejoin="round" 
                stroke-width="2" 
                d="M15 15l5 5M19 19l-5-5m0 0a7.5 7.5 0 01-10.607-10.607M4.393 4.393A7.5 7.5 0 0115 15z"
              />
            </svg>
          </div>
        </div>
        <button 
          type="submit" 
          :disabled="!isFormValid"
        >
          登录
        </button>
      </form>
      
      <div class="register-link">
        <p>
          还没有账号？
          <router-link to="/register">立即注册</router-link>
        </p>
      </div>
      
      <div v-if="errorMessage" class="error-message">
        {{ errorMessage }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const email = ref('')
const password = ref('')
const showPassword = ref(false)
const errorMessage = ref('')

const isFormValid = computed(() => {
  return email.value.length >= 3 && password.value.length >= 6
})

const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value
}

const handleLogin = async () => {
  errorMessage.value = ''
  console.log('开始登录流程，用户输入:', {
    email: email.value,
    passwordLength: password.value.length
  })

  if (!isFormValid.value) {
    errorMessage.value = '用户名至少3个字符，密码至少6个字符'
    return
  }

  try {
    const response = await fetch('/api/auth/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        identifyer: email.value.trim(),  // 改为 sid 
        password: password.value
      })
    })

    const data = await response.json()
    console.log('登录响应数据:', {
      状态码: response.status,
      响应头: Object.fromEntries(response.headers.entries()),
      响应体: data
    })

    if (!response.ok || data.code !== 0) {
      throw new Error(data.message || '用户名或密码错误')
    }

    // 计算token过期时间（24小时后）
    const expiresAt = new Date().getTime() + (24 * 1000 * 60 * 60 * 7)
    
    // 存储数据
    localStorage.setItem('token', data.data.token)
    localStorage.setItem('tokenExpires', expiresAt.toString())
    localStorage.setItem('user', JSON.stringify({
      creditLevel: data.data.user_info.credit_level,
      avatar: data.data.user_info.img,
      uid: data.data.user_info.uid,
      userName: data.data.user_info.user_name
    }))

    console.log('登录成功，存储的信息:', {
      token截断: data.data.token.substring(0, 20) + '...',
      过期时间: new Date(expiresAt).toLocaleString(),
      用户信息: data.data.user_info
    })

    router.push('/')
  } catch (error) {
    console.error('登录错误:', error)
    errorMessage.value = error.message || '登录失败，请稍后重试'
  }
}

// 檢查當前登錄狀態
const checkLoginStatus = () => {
  const userStr = localStorage.getItem('user')
  console.log('Current login status:', userStr ? JSON.parse(userStr) : 'Not logged in')
}

// 检查token是否过期
const checkTokenExpiration = () => {
  const tokenExpires = localStorage.getItem('tokenExpires')
  const token = localStorage.getItem('token')
  console.log('检查token状态:', {
    是否存在token: !!token,
    过期时间: tokenExpires ? new Date(parseInt(tokenExpires)).toLocaleString() : '未设置',
    当前时间: new Date().toLocaleString()
  })

  if (tokenExpires) {
    const now = new Date().getTime()
    if (now > parseInt(tokenExpires)) {
      console.log('Token已过期，执行退出登录操作')
      // token已过期，清除存储
      localStorage.removeItem('token')
      localStorage.removeItem('tokenExpires')
      localStorage.removeItem('user')
      router.push('/login')
    } else {
      console.log('Token仍然有效，剩余时间:', {
        剩余分钟: Math.round((parseInt(tokenExpires) - now) / 1000 / 60)
      })
    }
  }
}

onMounted(() => {
  email.value = ''
  password.value = ''
  checkLoginStatus()
  checkTokenExpiration()
  
  // 每分钟检查一次token状态
  const tokenCheckInterval = setInterval(() => {
    console.log('执行定期token检查')
    checkTokenExpiration()
  }, 60000) // 每分钟检查一次

  // 组件卸载时清除定时器
  onUnmounted(() => {
    clearInterval(tokenCheckInterval)
  })
})

// 修改返回功能
const goBack = () => {
  router.push('/') // 直接返回主页
}
</script>

<style scoped>
.login-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #ffffff;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.nav-header {
  height: 61px;
  background: #ffffff;
  display: flex;
  align-items: center;
  padding: 0 10px;
  position: relative;
  z-index: 1;
}

.back-icon {
  width: 24px;
  height: 24px;
  cursor: pointer;
  margin-left: 5px;
  position: absolute;
  left: 10px;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 22px;
  font-weight: 500;
  font-family: "SourceHanFontBold";
  color: #333333;
}

.login-container {
  padding: 30px 25px; /* 修改左右内边距 */
  max-width: 400px;
  margin: 0 auto; /* 删除上下margin，只保留水平居中 */
  background: #ffffff;
  color: #333;
  position: relative;
  height: calc(100vh - 61px); /* 调整高度，只减去导航栏高度 */
}

.login-container form {
  flex: none;           /* 添加 */
  margin-bottom: 20px;  /* 添加 */
}

.form-group {
  margin-bottom: 20px;
  width: 340px; /* 添加固定宽度 */
  margin-left: auto;
  margin-right: auto;
}

input {
  width: 340px; /* 修改输入框宽度 */
  height: 50px; /* 修改输入框高度 */
  padding: 0 12px; /* 调整内边距 */
  border: 1px solid #5b5b5b;
  border-radius: 8px;
  background-color: white;
  color: #333;
  margin-bottom: 10px;
  transition: border-color 0.2s;
  box-sizing: border-box; /* 确保padding不会影响整体宽度 */
}

input:focus {
  border-color: #3b82f6;
  outline: none;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-weight: 500;
  text-align: left; /* 确保左对齐 */
  padding-left: 0; /* 移除可能的左内边距 */
}

input::placeholder {
  color: #909399;
}

.password-wrapper {
  position: relative;
}

.toggle-password {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  width: 20px;
  height: 20px;
  cursor: pointer;
  color: #3b82f6;
  stroke: black;
}

button {
  width: 340px;
  height: 50px;
  margin-left: auto;
  margin-right: auto;
  margin-top: 40px;
  margin-bottom: 20px;  /* 添加底部边距 */
  display: block;
  background: #9dbce3;
  color: white;
  border: none;
  border-radius: 15px;
  cursor: pointer;
  font-size: 20px;
  transition: transform 0.2s ease-in-out;
}

button:hover:not(:disabled) {
  /* 只对未禁用的按钮应用hover效果 */
  transform: scale(1.02);
}

button:disabled {
  background-color: #939393; /* 将颜色从 #5b5b5b 改为更浅的 #939393 */
  cursor: not-allowed;
}

.register-link {
  position: static; /* 改为静态定位 */
  text-align: center;
  color: #5b5b5b;
  width: 100%;
  margin-top: 20px; /* 添加上边距 */
}

.register-link p {
  margin: 0;
  padding: 15px 0;
  font-size: 14px; /* 稍微调小字体 */
  line-height: 1.5;
  color: #5b5b5b;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 5px;
}

.register-link a {
  color: #3b82f6;
  text-decoration: none;
  margin-left: 5px; /* 给链接添加一些左边距 */
}

.error-message {
  color: red;
  text-align: center;
  margin-top: 10px;
}

input[type="password"]::-ms-reveal,
input[type="password"]::-ms-clear,
input[type="password"]::-webkit-credentials-auto-fill-button {
  display: none !important;
}

.btn-action {
  padding: 0.8rem 1.2rem;
  border: none;
  border-radius: 8px;
  background-color: #a5b2e5;
  color: #fff;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: background-color 0.2s;
}

.btn-action:hover {
  background-color: #8e9cd0;
}
</style>